package com.ypj.rpc.transport.socket.server;

import com.ypj.rpc.factory.ThreadPoolFactory;
import com.ypj.rpc.handler.RequestHandler;
import com.ypj.rpc.hook.ShutDownHook;
import com.ypj.rpc.provider.ServiceProviderImpl;
import com.ypj.rpc.registry.NacosServiceRegistry;
import com.ypj.rpc.serializer.CommonSerializer;
import com.ypj.rpc.serializer.KryoSerializer;
import com.ypj.rpc.transport.AbstractRpcServer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

/**
 * 监听某个端口循环接收请求，
 */
@Slf4j
public class SocketServer extends AbstractRpcServer {

    private final ExecutorService threadPool;
    private final CommonSerializer serializer;
    private final RequestHandler requestHandler=new RequestHandler();

    public SocketServer(String host, int port) {
        this(host,port,new KryoSerializer());
    }

    public SocketServer(String host, int port, CommonSerializer serializer) {
        this.host = host;
        this.port = port;
        this.serializer=serializer;
        threadPool= ThreadPoolFactory.createDefaultThreadPool("socket-rpc-server");
        serviceRegistry=new NacosServiceRegistry();
        serviceProvider=new ServiceProviderImpl();
        scanServices();
    }

    /**
     * 不再负责注册，只负责启动
     * @param
     */
    @Override
    public void start(){
        try (ServerSocket serverSocket=new ServerSocket()){
            serverSocket.bind(new InetSocketAddress(host,port));
            log.info("服务器正在启动...");
            ShutDownHook.getShutDownHook().addClearAllHook();
            Socket socket;
            while ((socket=serverSocket.accept())!=null){
                //log.info("客户端连接成功！Ip为："+socket.getInetAddress());
                log.info("消费者连接：{}：{}",socket.getInetAddress(),socket.getPort());
                threadPool.execute(new SocketRequestHandlerThread(socket,requestHandler,serializer));
            }
            threadPool.shutdown();
        } catch (IOException e) {
            log.error("服务器发生错误："+e.getMessage(),e);
        }
    }
}
